package com.juzipi.thread.test.demo1;

/**
 * @Author juzipi
 * @Date 2021/6/17 14:35
 * @Info
 */
public class DeadLock {
    public static void main(String[] args) {
        /*
        出现死锁的情况：
        1.互斥条件：一个资源每次只能被一个进程使用。
        2.请求与保持条件：一个进程因请求资源而阻塞时，对已获得的资源保持不放。
        3.不剥夺条件：进程已获得的资源，在未使用完之前，不能强行剥夺。
        4.循环等待条件：若干进程之间形成一种头尾相接的循环等待资源关系。
         */

        support support = new support(0,"土狗");
        support support1 = new support(2,"波斯猫");
        new Thread(support,"一").start();
        new Thread(support1,"二").start();
    }
}

class Dog{

}

class Cat{

}

class support implements Runnable{

    static final Dog dog = new Dog();
    static final Cat cat = new Cat();

    int choice;//选择
    String patName;//宠物名字


    public support(int choice, String patName) {
        this.choice = choice;
        this.patName = patName;
    }

    @Override
    public void run() {
        //养
        try {
            makeEat();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }

    private void makeEat() throws InterruptedException {
        if (choice == 0){
            synchronized (cat){
                System.out.println(this.patName+"获得猫的锁");
                Thread.sleep(100);
            }
                synchronized (dog){
                    System.out.println(this.patName+"获得狗的锁");
                }
        }
        else {
            synchronized (dog){
                System.out.println(this.patName+"获得狗狗的锁");
                Thread.sleep(1000);
            }
                synchronized (cat){
                    System.out.println(this.patName+"获得猫猫的锁");
                }
        }
    }

}